import cv2
from PySide6.QtCore import QThread,Signal,Qt
from PySide6.QtGui import QImage


class VideoProcessor(QThread):
    change_pixmap_signal = Signal(QImage)
    def __init__(self):
        super().__init__()
        self.video_path = None
        self.model =None
        self.running = False
        self.cap = None

    def set_video_path(self,video_path):
        self.video_path = video_path
        self.cap = cv2.VideoCapture(video_path)

    def set_model(self,model):
        self.model = model

    def run(self):
        if not self.video_path or not self.model:
            return
        self.running = True
        while self.running:
            if self.cap:
                ret, frame = self.cap.read()
                if not ret:
                    break
                #处理帧
                results = self.model(frame)
                rendered_frame = results.render()[0]
                #格式的转化——————————————————————————————————————————————
                rgb_image = cv2.cvtColor(rendered_frame, cv2.COLOR_BGR2RGB)
                h, w, ch = rgb_image.shape
                bytes_per_line = ch * w
                convert_to_qt_format = QImage(rgb_image.data, w, h, bytes_per_line, QImage.Format_RGB888)
                p = convert_to_qt_format.scaled(640, 480, Qt.KeepAspectRatio)  
                #————————————————————————————————————————————————————————————————————
                self.change_pixmap_signal.emit(p)
                cv2.waitKey(30) #控制帧率  

        if self.cap:
            self.cap.release()

    def stop(self):
        self.running = False

    def wait(self):
        self.quit()
        self.wait()